package ufp2p;

import java.io.*;
import java.net.*;

public class ScreenWriter implements Runnable {

	Socket sock;
	String message;
	
	public ScreenWriter(Socket sock)
	{
		this.sock = sock;
		System.out.println("<<<<<<<<<<<<Created a ScreenWriter for socket "+this.sock);
	}
	
	public void run()
	{
		try
		{
			readHandshakeMessage();
		}
		catch(Exception e)
		{
			System.out.println("Exception in Handshake "+e);
		}
	}
	
	private void readHandshakeMessage() throws Exception
	{
		System.out.println("<<<<<<<<<<<<<Waiting for Handshake");
		
		int bytesRead = 0;
		byte[] mybytearray;
        
        try {
            InputStream is = sock.getInputStream();
        	
            byte[] handshake = new byte[32];
				
			bytesRead = is.read(handshake, 0, 32);
				
			System.out.println("Bytes read in Handshake = "+bytesRead);
				
			if(bytesRead != 32)
					System.out.println("ERROR DIDNT READ THE WHOLE MESSAGE SIZE, ADD CODE TO FIX THIS, only read: " + bytesRead);
				
			PacketReader checkHandshake = new PacketReader(handshake, true);
			
			int peerId = checkHandshake.getPeerID();
			
			System.out.println(">>>>>>>>>>>>>From Handshake = "+peerId);
					
        }
        catch(Exception e)
        {
        	System.out.println("Exception while reading handshake "+e);
        }
				
	}
	
	public void readMessage() throws Exception
	{
		System.out.println("<<<<<<<<<<<<Running ScreenWriter Thread");
		int current = 0;
        int bytesRead;
        byte[] mybytearray;
        

		
		
        try {
            InputStream is = sock.getInputStream();
        	
            for(int j=1; j <= PeerProcess.NumberOfPieces; j++)
            {
            	
            
				System.out.println("<<<<<<<<<<<<Waiting for partSize "+j+"....");
				//Start Reading the Header
				
				//Next Header Item is messageSize byte[4]
				byte[] messageSize = new byte[4];
				
				bytesRead = is.read(messageSize, 0, messageSize.length);
				
				System.out.println(bytesRead);
				
				if(bytesRead != 4)
					System.out.println("ERROR DIDNT READ THE WHOLE MESSAGE SIZE, ADD CODE TO FIX THIS, only read: " + bytesRead);
				
				String temp = "";
				
				for(int i=0; i<4; i++)
				{
					if(messageSize[i] != 0)
					{ 
						temp = temp + (char)(messageSize[i]);
					}
					
					System.out.println(temp);
				}
					
				
				//convert the byte[] into an int
				String strMessageSize = new String(messageSize);
				int intMessageSize = Integer.parseInt(temp);
				
				
				
	            System.out.println("<<<<<<<<<<<<Found partSize=" + intMessageSize);
				
				System.out.println("<<<<<<<<<<<<Receiving file...");
				mybytearray  = new byte [intMessageSize];
	            FileOutputStream fos = new FileOutputStream("New_"+PeerProcess.FileName+j+".sp");
	            BufferedOutputStream bos = new BufferedOutputStream(fos);
	            bytesRead = is.read(mybytearray,0,mybytearray.length);
	
	            current = bytesRead;
	            
	
	            do {
	               bytesRead =
	                  is.read(mybytearray, current, (mybytearray.length-current));
					  
	               if(bytesRead >= 0) {
	                   //System.out.println("Length in if "+mybytearray.length);
	                   current += bytesRead;
	                   int value = current;
	                   System.out.println("<<<<<<<<<<<< ???" + value);
	               }
	               System.out.println("IN WHILE LOOP!!!");
	
	            } while(bytesRead > 0);
	         
	            bos.write(mybytearray, 0 , current);
	
	            //System.out.println("a while");
	            bos.flush();
	            //long end = System.currentTimeMillis();
	           // System.out.println(end-start);
	            bos.close();
	            fos.close();
	            
	            System.out.println("<<<<<<<<<<<<File Part "+j+" created!!");
            }
            
            Splitter joinFile = new Splitter();
            joinFile.join();
	/*	while(true)
		{
			try{
		        message = inFromServer2.readLine();
		        System.out.println("FROM CLIENT: " + message);
		        
		        
			}
			catch(Exception e)
			{}
		}*/
        }catch(Exception e){
        	System.out.println("<<<<<<<<<<<Exception = "+e);
        }
	}
}
